"use client";

import { Loader2, TriangleAlert } from "lucide-react";
import { useMemo, useState } from "react";

import { useProjectsQuery } from "@/hooks/use-projects-query";
import { downloadCSV } from "@/lib/csv";
import type { ProjectSummary } from "@/lib/types";

interface ReportsViewProps {
  initialProjects: ProjectSummary[];
}

export function ReportsView({ initialProjects }: ReportsViewProps) {
  const [selectedMonth, setSelectedMonth] = useState(() => {
    const now = new Date();
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
  });

  const { data: projects, isLoading, error } = useProjectsQuery(initialProjects);

  const totals = useMemo(() => {
    if (!projects || projects.length === 0) {
      return {
        monthlyTarget: 0,
        currentValue: 0,
      };
    }

    return projects.reduce(
      (acc, project) => {
        acc.monthlyTarget += project.monthlyTarget ?? 0;
        acc.currentValue += project.currentValue ?? 0;
        return acc;
      },
      { monthlyTarget: 0, currentValue: 0 },
    );
  }, [projects]);

  const handleExport = () => {
    if (!projects || projects.length === 0) {
      return;
    }

    downloadCSV(
      `schedule-report-${selectedMonth}.csv`,
      [
        { key: "name", header: "项目" },
        { key: "monthlyTarget", header: "当月目标" },
        { key: "currentValue", header: "当前产值" },
        { key: "progressPercentage", header: "进度%" },
      ],
      projects.map((project) => ({
        name: project.name,
        monthlyTarget: project.monthlyTarget ?? "",
        currentValue: project.currentValue ?? "",
        progressPercentage: project.progressPercentage ?? "",
      })),
    );
  };

  if (isLoading && (!projects || projects.length === 0)) {
    return (
      <div className="flex min-h-[200px] items-center justify-center rounded-lg border border-border bg-card/60">
        <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (!projects || projects.length === 0) {
    return (
      <div className="rounded-lg border border-dashed border-border bg-card/50 p-6 text-sm text-muted-foreground">
        暂无报表数据。请确认排产信息已录入，或稍后再试。
      </div>
    );
  }

  return (
    <div className="space-y-5">
      <div className="flex flex-col gap-3 rounded-lg border border-border bg-card p-4 shadow-sm sm:flex-row sm:items-center sm:justify-between">
        <div>
          <p className="text-sm font-medium text-foreground">筛选项</p>
          <p className="text-xs text-muted-foreground">当前仅支持选择月份，后续将补充更多条件。</p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <label className="text-xs text-muted-foreground" htmlFor="report-month">
            月份
          </label>
          <input
            id="report-month"
            type="month"
            value={selectedMonth}
            onChange={(event) => setSelectedMonth(event.target.value)}
            className="rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary"
          />
          <button
            type="button"
            onClick={handleExport}
            className="inline-flex items-center rounded-md bg-primary px-3 py-2 text-xs font-medium text-primary-foreground transition hover:bg-primary/90"
          >
            导出 CSV
          </button>
        </div>
      </div>

      {error ? (
        <div className="flex items-center gap-2 rounded-lg border border-destructive/40 bg-destructive/5 px-4 py-3 text-xs text-destructive">
          <TriangleAlert className="h-4 w-4" />
          报表数据刷新失败，请稍后重试。
        </div>
      ) : null}

      <div className="grid gap-3 rounded-lg border border-border bg-card p-4 shadow-sm sm:grid-cols-2">
        <div>
          <p className="text-xs text-muted-foreground">总目标产值</p>
          <p className="text-lg font-semibold text-foreground">
            {totals.monthlyTarget.toLocaleString(undefined, { maximumFractionDigits: 2 })}
          </p>
        </div>
        <div>
          <p className="text-xs text-muted-foreground">当前累计产值</p>
          <p className="text-lg font-semibold text-foreground">
            {totals.currentValue.toLocaleString(undefined, { maximumFractionDigits: 2 })}
          </p>
        </div>
      </div>

      <div className="overflow-hidden rounded-lg border border-border">
        <table className="min-w-full divide-y divide-border text-sm">
          <thead className="bg-muted/40 text-muted-foreground">
            <tr>
              <th className="px-4 py-3 text-left font-medium">项目</th>
              <th className="px-4 py-3 text-left font-medium">当月目标</th>
              <th className="px-4 py-3 text-left font-medium">当前产值</th>
              <th className="px-4 py-3 text-left font-medium">进度</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border bg-card">
            {projects.map((project) => (
              <tr key={project.id}>
                <td className="px-4 py-3">
                  <div className="flex flex-col">
                    <span className="font-medium text-foreground">{project.name}</span>
                    <span className="text-xs text-muted-foreground">编号：{project.id}</span>
                  </div>
                </td>
                <td className="px-4 py-3 text-muted-foreground">
                  {project.monthlyTarget != null ? project.monthlyTarget.toLocaleString() : "--"}
                </td>
                <td className="px-4 py-3 text-muted-foreground">
                  {project.currentValue != null ? project.currentValue.toLocaleString() : "--"}
                </td>
                <td className="px-4 py-3">
                  <div className="flex items-center gap-3">
                    <div className="h-2 w-32 overflow-hidden rounded-full bg-muted">
                      <div
                        className="h-2 rounded-full bg-primary"
                        style={{ width: `${Math.min(project.progressPercentage ?? 0, 100)}%` }}
                      />
                    </div>
                    <span className="text-xs font-medium text-primary">
                      {project.progressPercentage != null ? `${project.progressPercentage}%` : "--"}
                    </span>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
